package com.wlc.socket.demo01;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description Socket 客户端
 * @date 2021-07-15 13:06
 */
public class SocketClient {

    public static void main(String[] args) {
        method2();
    }

    private static void method2() {
        // 连接到本机的8888端口
        try {
            System.out.println("启动客户端");
            Socket s = new Socket("127.0.0.1", 8888);
            // 字节输出流
            OutputStream outputStream = s.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            InputStream inputStream = s.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);

            while (true) {
                Scanner sc = new Scanner(System.in);
                String line = sc.next();
                System.out.println("客户端发送完毕");
                dataOutputStream.writeUTF(line);
                System.out.println("客户端收到服务端的信息为：" + dataInputStream.readUTF());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端发送数据，然后让服务端接收数据
     */
    private static void method01() {
        // 连接到本机的8888端口
        try {
            System.out.println("启动客户端");
            Socket localhost = new Socket("127.0.0.1", 8888);
            // 字节输出流
            OutputStream outputStream = localhost.getOutputStream();
            // 把字节输出流封装成数据输出流
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            Scanner sc = new Scanner(System.in);
            String line = sc.nextLine();

            dataOutputStream.writeUTF(line);
            System.out.println("客户端发送完毕");
            localhost.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
